/**
 * FileName: CorsConfig
 * Author: Wb
 * Date: 2025/9/26 9:45
 * Description: 解决前端跨域问题
 * History:
 */
package org.test.device.config.web;

import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.test.device.config.jwt.LoginInterceptor;

/**
 * 〈一句话功能简述〉<br>
 * 〈解决前端跨域问题〉
 *
 * @author Wb
 * @create 2025/9/26
 * @since 1.0.0
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // 使用 allowedOriginPatterns 允许所有来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*"); // 使用 allowedOriginPattern 允许所有来源
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**") // 需要登录的接口路径（如所有/api下的接口）
                .excludePathPatterns(       // 放行的公开接口（无需登录）
                        "/auth/login",        // 登录接口
                        "/auth/refresh-token", // 刷新Token接口
                        "/doc.html" ,//knife4j文档接口
                        // Knife4j 静态资源（JS/CSS/图标等）
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/v3/api-docs/**",
                        "/v2/api-docs/**",
                        "/swagger-ui.html/**",
                        "/swagger-ui/**"
                );
    }
}